package com.cybertron.ironhide.manage.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class InitializeBean implements ServletContextListener {

	private static final Log logger = LogFactory.getLog(InitializeBean.class);

	private final String LOCATION = "classpath:ironhide.properties";

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
		if (logger.isDebugEnabled()) {
			logger.debug("loading properties...");
		}
		ResourceLoader loader = new DefaultResourceLoader();
		Resource resource = loader.getResource(LOCATION);
		InputStream is = null;
		Properties prop = new Properties();

		try {
			is = resource.getInputStream();
			prop.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}

		Constants.IS_DEBUG = Boolean.valueOf(prop.getProperty("IS_DEBUG",
				"false"));

		Constants.RESOURCE_ROOT_PATH = prop.getProperty("RESOURCE_ROOT_PATH");

		Constants.RESOURCE_ROOT_URL = prop.getProperty("RESOURCE_ROOT_URL");

		Constants.API_ROOT_URL = prop.getProperty("API_ROOT_URL");

		Constants.INDEX_FILE_PATH = prop.getProperty("INDEX_FILE_PATH");

		Constants.ASSOCIATE_TAG = prop.getProperty("ASSOCIATE_TAG");

		Constants.SOLR_SERVER = prop.getProperty("SOLR_SERVER");

		Constants.MAX_SITE_CRAWL_COUNT = Integer.valueOf(prop
				.getProperty("MAX_SITE_CRAWL_COUNT"));

		Constants.WEB_ROOT_PATH = prop.getProperty("WEB_ROOT_PATH");

		Constants.SEARCH_CONTEXT_PATH = prop.getProperty("SEARCH_CONTEXT_PATH");

		Constants.TAG_PATH = prop.getProperty("TAG_PATH");

		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (prop != null) {
			prop.clear();
		}
		if (logger.isDebugEnabled()) {
			logger.debug("loaded properties...");
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

}
